package com.eqdd.yiqidian.ui;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;

import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RichEditorActivityCustom;
import com.eqdd.yiqidian.WriteActivityCustom;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.WriteBean;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.widget.ChooseAlertView;
import com.eqdd.yiqidian.widget.EditDialogFragment;
import com.gamerole.richtextview.RichEditor;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.net.URI;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author吕志豪 .
 * @date 18-1-29  上午10:50.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class RichEditorActivity extends BaseActivity implements ColorChooserDialog.ColorCallback {
    private RichEditor mEditor;
    private RichEditorActivityCustom dataBinding;
    private EditDialogFragment editDialog;
    private String msg;
    private WriteBean writeBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isKeyBoardJustPan = false;
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_rich_editor);
        initTopRightText("完成", v -> {
            if (checkParam()) {
                dataBinding.editor.getText(s -> {
                    WriteBean writeBean = new WriteBean();
                    writeBean.setHtml(mEditor.getHtml());
                    String textContent = s.length() > 60 ? s.substring(0, 60) : s;
                    writeBean.setTextContent(textContent);
                    String imgUrl = getImgUrl(dataBinding.editor.getHtml());
                    writeBean.setImgUrl(imgUrl);
                    Intent intent = new Intent();
                    intent.putExtra(Config.BEAN, writeBean);
                    setResult(Config.SUCCESS, intent);
                    finish();
                });
            } else {
                ToastUtil.showShort(msg);
            }
        });
    }

    @Override
    public void initData() {
        writeBean = (WriteBean) getIntent().getSerializableExtra(Config.BEAN);
        String title = getIntent().getStringExtra(Config.TITLE);
        initTopTitleBar(View.VISIBLE, title);
    }

    @Override
    public void setView() {
        mEditor = findViewById(R.id.editor);
        mEditor.requestFocus();
        mEditor.setEditorHeight(200);
        mEditor.setEditorFontSize(22);
        mEditor.setEditorFontColor(Color.BLACK);
        mEditor.setPadding(10, 10, 10, 10);
        mEditor.setPlaceholder("内容");
        findViewById(R.id.action_bold).setOnClickListener(v -> mEditor.setBold());

        findViewById(R.id.action_italic).setOnClickListener(v -> mEditor.setItalic());


        findViewById(R.id.action_heading1).setOnClickListener(v -> mEditor.setHeading(1));

        findViewById(R.id.action_heading2).setOnClickListener(v -> mEditor.setHeading(2));

        findViewById(R.id.action_heading3).setOnClickListener(v -> mEditor.setHeading(3));

        findViewById(R.id.action_heading4).setOnClickListener(v -> mEditor.setHeading(4));
        findViewById(R.id.action_insert_line).setOnClickListener(v -> mEditor.insertHtml("<p style=\"border-top :1px solid #d9d9d9; padding: 20px 10px 0px 10px \"></p >"));

        findViewById(R.id.action_txt_color).setOnClickListener(v -> new ColorChooserDialog.Builder(RichEditorActivity.this, R.string.app_name)
                .allowUserColorInput(false)
                .customButton(R.string.md_custom_label)
                .presetsButton(R.string.md_presets_label)
                .show(getSupportFragmentManager()));


        findViewById(R.id.action_insert_image).setOnClickListener(v -> PicUtil.single(RichEditorActivity.this, true));

        findViewById(R.id.action_insert_link).setOnClickListener(v -> showLinkDialog());
        if (writeBean != null) {
            mEditor.setHtml(writeBean.getHtml());
        }
    }

    private String getImgUrl(String html) {
        // 按指定模式在字符串查找
        String pattern = "<img[\\S\\s]*?\"([\\s\\S]*?)\"[\\S\\s]*?>";

        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);

        // 现在创建 matcher 对象
        Matcher m = r.matcher(html);
        if (m.find()) {
            if (m.groupCount() > 0) {
                String url = m.group(1);
                return URI.create(url).getPath();
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    private boolean checkParam() {
        if (TextUtils.isEmpty(dataBinding.editor.getHtml())) {
            msg = "请输入内容";
            return false;
        }
        return true;
    }

    private void showLinkDialog() {
        editDialog = ChooseAlertView.getEditDiglog("添加链接", "请输入文字", "请输入链接地址", (content) -> {
            if (TextUtils.isEmpty(content.get(0)) || TextUtils.isEmpty(content.get(1))) {
                ToastUtil.showLong("信息不完整，添加失败");
                return;
            } else {
                Pattern compile = Pattern.compile("^http(|s)://");
                Matcher matcher = compile.matcher(content.get(1));
                if (matcher.find()) {
                    mEditor.insertLink(content.get(1), content.get(0));
                } else {
                    mEditor.insertLink("http://" + content.get(1), content.get(0));
                }

            }
        });
        editDialog.show(getSupportFragmentManager(), "edit");
    }

    @Override
    public void onColorSelection(@NonNull ColorChooserDialog dialog, int selectedColor) {
        mEditor.setTextColor(selectedColor);
    }

    @Override
    public void onColorChooserDismissed(@NonNull ColorChooserDialog dialog) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedias = PictureSelector.obtainMultipleResult(data);
            HttpUtil.upLoadPic(RichEditorActivity.this, localMedias.get(0).getCompressPath(),
                    url -> mEditor.insertImage(url, "图片", 100));
        }
    }
}
